import { Dialog } from "@/hoc/Diolog";
import apiStore from "@/stores/apiStore";
import { CommodityListType, TeaItemListType, serviceConfig } from "@Tea/model";
import { isSuccessCode, useElMessageBox, useGloablLoading } from "@Tea/utils";
import { PropType, Ref, defineComponent, ref, watch } from "vue";
import { ElMessage, ElUpload, UploadRequestOptions ,ElImage,ElIcon} from "element-plus"
import axios from "axios"
import { Plus,CircleCloseFilled } from "@element-plus/icons-vue"
import commonClass from "./common.module.scss"
import teaItemDialog from './TeaItemDialog.module.scss' 
import { httpCommonHandle } from "@/utils/httpUtils";

export default defineComponent({
  props: {
    visible: {
      type: Object as PropType<Ref<boolean>>,
      required: true
    },
    targetTeaId: {
      type: Object as PropType<Ref<CommodityListType["teaId"] | ''>>,
      required: true
    }
  },
  setup(props) {
    // loading
    const loading = ref(false)
    // 更多图片
    const itemList = ref<TeaItemListType[]>([])
    const baseUrl = `http://127.0.0.1:${serviceConfig.port}/`
    const { getTeaItems, addTeaItem , delTeaItem} = apiStore().api
    const { showLoading, closeLoading } = useGloablLoading()


    // 监听茶叶id，每次发生变化就请求数据
    watch(props.targetTeaId, async (newVal, oldVal) => {
      if (newVal !== "") {
        try {
          loading.value = true
          const { code, data, msg } = await getTeaItems({ teaId: newVal })
          loading.value = false

          if (isSuccessCode(code)) {
            itemList.value = data

            data.length === 0 && ElMessage({
              type: "warning",
              message: "当前商品没有更多详情图！"
            })
          } else {
            useElMessageBox({
              type: "warning",
              content: msg
            })
          }
        } catch (e) {
          loading.value = false
          useElMessageBox({
            type: "error",
            content: e
          })
        }
      }
    })

    // 添加
    const handleAddTeaItem = async (itemCover: string) => {
      try {
        const { code, msg,data } = await addTeaItem({
          itemCover,
          teaId: props.targetTeaId.value as number
        })
        
        loading.value = false
        if (isSuccessCode(code)) {
          ElMessage({
            type: "success",
            message: msg
          })
          itemList.value.push({
            itemId: data,
            itemCover
          })
        }
      } catch (e) {
        console.log(e);
        loading.value = false
      }
    }

    // 删除
    const delItem = (itemId: TeaItemListType['itemId'], index: number) => {
      useElMessageBox({
        content: "确定要删除吗？",
        thenCallback:async () => {
          httpCommonHandle({
            loading: useGloablLoading,
            callBack: () => delTeaItem(itemId),
            onSuccess: () => {
              itemList.value.splice(index, 1)
            }
          })
        }
      })
    }

    const curstomHttp = async (option: UploadRequestOptions) => {
      try {
        loading.value = true
        const form = new FormData(); // FormData 对象
        form.append("file", option.file); // 文件对象  'upload'是后台接收的参数名
        axios.post('/api/admin/upload', form).then( async (res) => {
          loading.value = false
          if (isSuccessCode(res.data.code)) {
            const itemCover = res.data.data
            await handleAddTeaItem(itemCover)
          }
        }).catch(e => {
          loading.value = false
        })
        
      } catch (e) {
        console.log(e);
      }
      option.file
    }

    // 列表组件
    const ItemList = () => (
      <div class={teaItemDialog.teaItemList} v-loading={loading.value}>
        {
          itemList.value.map((item, index)=>{
            const url = `${baseUrl}${item.itemCover}`
            return (
              <div class={`${teaItemDialog.imgBox}`}>
                <span onClick={() => delItem(item.itemId, index)} class={`${teaItemDialog.delIcon}`}>
                  <ElIcon size={24} ><CircleCloseFilled /></ElIcon>
                </span>
                <ElImage
                  key={item.itemId}
                  previewSrcList={[url]}
                  class={`${commonClass.upload_picture} ${teaItemDialog.imageItems}`}
                  fit="cover"
                  src={url}>
                </ElImage>
              </div>
            )
          })
        }
        <ElUpload
          showFileList={false}
          httpRequest={curstomHttp}
        >
          {
            <ElIcon class={`${commonClass.upload_picture} ${commonClass.upload_border}`}><Plus  /></ElIcon>
          }
        </ElUpload>
      </div>
    )

    return () => (
      Dialog({
        visible: props.visible,
        notUseFooter: true,
        content: ItemList,
        title: "管理商品详情图",
        onClose: () => {
          loading.value = false
        }
      })
    )
  }
})